<?php
namespace Zuopin\Controller;
use Think\Controller;


class IndexController extends Controller
{
    /**
     * 学生作品控制器
     * 
     */
    public function _initialize()
    {
        $this->curYear=D('Year')->where('cur=1')->getfield('year');
        $this->curTerm=D('YearTerm')->where('cur=1')->getfield('term');
        $this->jfclassModel=D('JfClass');
        $this->zuopinModel=D('Zuopin/Zuopin');
        $this->rootPath = './Uploads/zuopin/';

	   	$menu_list = ['first'=>['title' => '作品','tab'=>'zuopin']];


        if (get_uid()) {
            $aClass = cookie('aClassInfo');
            
            $classlist = $this->jfclassModel->field('id,bj_code,bj_name')->order(array('bj_code'=>'asc'))->select();
            $this->assign('classlist', $classlist); 
            $bj_code=I('bj_code',$aClass['bj_code']);
            $c_map['bj_code']=$bj_code;
            $bj_name=$this->jfclassModel->where($c_map)->getField('bj_name');
             foreach ($classlist as $child) {
                    $children[] = array('tab' => 'class_'.$child['bj_code'], 'title' => $child['bj_name'],
                     'href' => U('Zuopin/index/index', array('bj_code' => $child['bj_code'])));
                }


            $menu_list['right'] = [
            	['tab' => 'post', 'title' => '上传作品', 'href' => '#frm-post-popup', 'a_class'=>'open-popup-link']
            ] ;
        }else{
        	$bj_name="全部班级";
        	if (isset($children)) unset($children);
        	$children[]=['tab'=>'class','title'=>'全部班级',
                  'href' => U('Zuopin/index/index')];
        }
        

        //传递菜单信息
        $menu_list['left'] = [
			                         ['tab' => 'home', 'title' => '我的班级', 'href' => U('Zuopin/index/index'),'icon'=>'home',],
                                 ['tab' => 'class', 'title' => $bj_name, 
                                 'href' => U('Zuopin/index/index',array('bj_code' => $bj_code)), 'icon'=>'th',
                                 'children'=>$children,
                                 ],  
	                          ];
 		    if (isset($children)) unset($children); 
        $this->assign('tab','home');        
        $this->assign('sub_menu', $menu_list);

    }

    public function index($page = 1, $class_id = 0,$bj_code=0)
    {
       $user_info=query_user(array('nickname'));
       
        //设置展示方式 列表；瀑布流
        $aDisplay_type=I('display_type','list','text');
        $cookie_type=cookie('issue_display_type');
        if($aDisplay_type==''){
            if($cookie_type){
                $aDisplay_type=$cookie_type;
            }else{
                $aDisplay_type=modC('DISPLAY_TYPE','list','Issue');
                cookie('issue_display_type',$aDisplay_type);
            }
        }else{
            if($cookie_type!=$aDisplay_type){
                cookie('zuopin_display_type',$aDisplay_type);
            }
        }
        $this->assign('display_type',$aDisplay_type);
        //设置展示方式 列表；瀑布流 end
        //
        if(empty($bj_code)){                  
          if(isset($map['bj_code'])) unset($map['bj_code']);
          $map['is_top'] = 1;  //所有班级时仅显示推荐的作品
        }else{
            $map['bj_code']=$bj_code;
        }

        $aClass = cookie('aClassInfo');//获取登录时cookie班级信息
        $lessonList=M('CourseXinxijishu')->field('id,title')->where(array('grade'=>$aClass['course_grade']))->select();

        $map['status'] = 1;
        $content = $this->zuopinModel->where($map)->order(array('create_time'=>'desc'))->page($page, 16)->select();
        $totalCount = $this->zuopinModel->where($map)->count();
        if(count($content)){
            foreach ($content as &$v) {
                $v['user'] = query_user(array('id', 'nickname', 'space_url', 'space_link', 'avatar128', 'rank_html'), $v['uid']);
               
                if($aDisplay_type=='masonry'){
                    $cover = M('Picture')->where(array('status' => 1))->getById($v['cover_id']);
                    $imageinfo = getimagesize('.'.$cover['path']);
                    $v['cover_height']=$imageinfo[1]*255/$imageinfo[0];
                    $v['cover_height']=$v['cover_height']?$v['cover_height']:253;
                }
            }
            unset($v);
        }
  
        
        $this->assign('contents', $content);
        if (D('Common/Module')->isInstalled('Weibo')) { //安装了微博模块
            $this->assign('sendWeibo', true);//变量名称区分大小写
	        } 
        
        $user_info = cookie('aUser');
       // dump(cookie());die;


        $this->assign('totalPageCount', $totalCount);
        $this->assign('aUser',$user_info);

        $this->assign('aClass',$aClass);
        $this->assign('keti',$lessonList);
		    $this->assign('aContent','作者：'.$user_info['nickname']);

        $this->tab = $bj_code==''?'home':'class';//tab标签active        
        $this->setTitle('作品');
        $this->display();
    }

    public function doPost($id = 0)
    {
        
        $uid=is_login();
        if (!is_login()) {
            $this->error('请登陆后再上传。');
        }else{
            $user=D('Member')->where(array('uid'=>is_login()))->field('bj_code,st_code, nickname')->find();//session('user_auth');
            $user['bj_name']=get_bjname($user['bj_code']);
            $this->checkAuth('Zuopin/Index/addPost',is_login(),'没有权限上传作品');
        }

        $aSendWeibo = I('sendWeibo', 0, 'intval');
        // dump($aSendWeibo);die;
        $lid=I('lid',session('user_auth.lid'),'int');
        $content=trim(op_h(I('post.content')));
        if($lid){
            $xinxi=M('CourseXinxijishu')->getById($lid);
            $xinxi['title']=trimall($xinxi['title']);//去除标题中的空格
        }else{
           $this->error('请选择标题。');
        } 
        if ($content== '') {
            $this->error('请输入作品介绍。');
        }else{
            $data['content']=$content;
        }
        $myclass=M('JfClass')->where(array('bj_code'=>$user['bj_code']))->find();
           $savepath=$this->curTerm.'/'.$user['bj_code'].'/';
        
           $saveName= $xinxi['title'].'_'.$myclass['bj_name'].substr($user['st_code'],-2).$user['nickname'];
    
        // 上传作业默认增加多少积分（默认值为20）
         $default_score = modC('DEFAULT_SCORE',20,'zuopin');
         // dump($default_score);die;
         $this->checkActionLimit('zuopin_add_post','Zuopin',null,get_uid());//die;
           $config = array(
                'maxSize'    =>   50*1024*1024, // 设置附件上传大小
                'rootPath'   =>    $this->rootPath,
                'savePath'   =>    $savepath,
                'saveName'   =>    $saveName,//iconv('utf-8', 'gbk', $saveName),//uniqid(),//已在THINKPHP中修改支持中文文件名上传
                'exts'       =>    $xinxi['allow_ext'],//str2arr($xinxi['allow_ext']),
                'autoSub'    =>    true,
                'subName'    =>    $myclass['grade'].I('post.lid'),
             );

             $upload = new \Think\Upload($config);// 实例化上传类 
             //dump($upload);
             $info   =  $upload->upload();
             //dump($info);
             //$file_ext = pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION );
            if(!$info) {
                        // 上传错误提示错误信息
                        $this->error($upload->getError(),Cookie('__forward__'),3);
                    }else{
                    // 上传成功保存表单数据                      
                    $url= $info['file']['savepath'].$saveName.'.'.$info['file']['ext'];                     
                    $updata=array_merge($data,array(                         
                         'lid'        => $lid,
                         'title'      => $xinxi['title'],
                         'bj_name'    => $user['bj_name'],
                         'bj_code'    => $user['bj_code'],
                         'st_code'    => $user['st_code'],                                           
                         'grade'      => $myclass['course_grade'],
                         "name"       => $user['nickname'], 
                         'keyword'    => $user['bj_name'].','.$user['nickname'].',['. $lid.'],'.$xinxi['title'],
                         'md5'        => $info['file']["md5"],
                         "file_url"   => $url,                       
                         "file_name"  => $info['file']['name'],
                         'file_ext'   => $info['file']["ext"] ,                         
                         "term"       => $this->curTerm,
                         'score'      => $default_score
                         ) 
                        );

                    
         $data = $this->zuopinModel->create($updata);


         $res=$this->zuopinModel->add($data);

             if($res){
                
		         /*发送上传作品成功提示消息*/
		         $tip='积分+'.$default_score;
             
             $title_ms = '作业提交成功！';
             $content_ms=$user['nickname'].":恭喜您!成功上传了一次作业。课题：".$xinxi['title'] .' ('.$tip.')';
             $url_ms='Zuopin/index/contentdetail';
             $to_uid=$uid;
             // dump($to_uid);
             
             $issendmessage=modC('SEND_MESSAGE', 1,'Zuopin');
              if($issendmessage){    
                 D('Common/Message')->sendMessageWithoutCheckSelf($to_uid, $title_ms, $content_ms, $url_ms, array('id'=>$res), 1, 0);
               }
             /*上传增加积分*/                
                $scoreModel= D('Ucenter/Score') ;
                // dump($scoreModel);die;
                $remark=$user['bj_name'].$user['nickname']."上传作品成功，".$tip;//记录参数
                $scoreModel->setUserScore($uid, $default_score, '1', 'inc','zuopin', $uid,$remark);
                //$scoreModel->setUserScore($uids, $score, $type, $action = 'inc',$action_model ='',$record_id=0,$remark='');
                

	            //同步推送至微博
	            if ($aSendWeibo) {
	                    //开始发布微博	public function addWeibo($uid, $content = '', $type = 'feed', $feed_data = array(), $from = '')  
                    $feed_data=array(
                      'title'=>$xinxi['title'],                      
                      'site_link'=>$_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].U('contentdetail', array('id' => $res)),
                      'from'=>'作品分享',
                      ) ; 
                          // dump($feed_data);die;
	                    if ($isEdit) {
                        $feed_data['content']='我修改了作品'."【" . $title . "】";
	                        D('Weibo/Weibo')->addWeibo($uid, '我修改了作品'."【" . $xinxi['title'] . "】：" . U('contentdetail', array('id' => $res)),  $type, $feed_data=array('id' =>$res),"zuopin");
	                    } else {
                        //dump($feed_data);die;
                        $feed_data['content']='我上传了一个新的作品'."【" . $xinxi['title'] . "】";
	                        D('Weibo/Weibo')->addWeibo($uid, '我上传了一个新的作品'."【" . $xinxi['title'] . "】：" .$feed_data['site_link'], $type='feed', $feed_data, $feed_data['from']);
	                    }
	                }
                    $this->success('上传成功！'. $tip);                    
                 }else{
                    $this->success('保存失败！');
                 }
      }
    }

    public function contentDetail($id = 0)
    {
       $id=I('id');
        $zuopinModel=$this->zuopinModel;
        $content = $zuopinModel->find($id);
 
        if (!$content) {
            $this->error('404 not found');
        }
        $zuopinModel->where(array('id' => $id))->setInc('view_count');
        $this->assign('issue_id', $issue['id']);
        $content['user'] = query_user(array('id', 'nickname', 'space_url', 'space_link', 'avatar64', 'rank_html', 'signature'), $content['uid']);

        // dump($content);die;

        $this->assign('content', $content);

        $this->setTitle('{$content.title|op_t}' . '——作品');
        $this->setKeywords($content['title']);

         $return = array('status' => 1, 'info' =>'上传成功', 'data' => '');

        $this->display();
    }



/*下载作品
 * @水月居
 */
    public function downloadFile($id=null){
        $id=I('id','','intval');
        // dump($id);
        if (empty($id) || !is_numeric($id)) {
            $this->error('参数错误');
        }
        $fileModel=$this->zuopinModel;

        // dump($fileModel);
        $file=$fileModel->find($id);
 
        // dump($file);die;
        if(empty($file)){
            $this->error( '找不到对应的id='."{$id}".'文件');
            return false;
        }
      
        $root = $this->rootPath;
        $call = '';
        if(false === $fileModel->downLocalFile($root, $id, $call, $info['id'])){
            $this->error( $fileModel->getError());
        }

    }
   /**@todo
  *下载附件*
  **/
   public function download(){
    $id=I('fid');
    $afile=$this->zuopinModel->find($id);

    //判断文件是否存在
    $_rootPath=$this->_ROOTPATH;
   
    $file_path=$_rootPath.$afile['file_url'];
   // dump($file_path);//die;

    /**处理可能存在中文名的路径*/
    $file_path_gb = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码    
    if (file_exists($file_path)) {
      $file_path=$file_path;     
    }elseif(file_exists($file_path_gb)){
    $file_path=$file_path_gb;
    }else{
      $this->error('文件'.$file_path.'不存在！'); 
    }

    $file_name = str_replace(' ','',$afile['file_name']);  //获取文件名称 basename()
    $file_size = filesize($file_path); //获取文件大小

    $fp = fopen($file_path, 'r'); //以只读的方式打开文件
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: {$file_size}");
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                 header('Content-Disposition: attachment; filename="' . rawurlencode($file_name) . '"');
             } else {
                 header('Content-Disposition: attachment; filename="' . $file_name . '"');
             }
    //header("Content-Disposition: attachment;filename={$file_name}");
    $buffer = 2048;
    $file_count = 0;
    //判断文件是否结束
    while (!feof($fp) && ($file_size-$file_count>0)) {
    $file_data = fread($fp, $buffer);
    $file_count += $buffer;
    echo $file_data;
    }
    fclose($fp); //关闭文件
    }

    /**用于表单自动上传图片的通用方法
     * @auth 陈一枭
     */
    public function uploadFile()
    {
        $return = array('status' => 1, 'info' =>'上传成功', 'data' => '');
        /* 调用文件上传组件上传文件 */
        $File = $this->zuopinModel;
        $driver = 'local';
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);
        $info = $File->upload(
            $_FILES,
            $this->rootPath,//C('ZUOPIN_UPLOAD'),
            $driver,
            $uploadConfig
        );


        /* 记录附件信息 */
        if ($info) {
            $return['data'] = $info;
        } else {
            $return['status'] = 0;
            $return['info'] = $File->getError();
        }


        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }


    public function edit($id)
    {
        // if (!check_auth('addZuopin') && !check_auth('editZuopin')) {
        //     $this->error('抱歉，您不具备修改权限。');
        // }
        $content = $this->zuopinModel->find($id);
        if (!$content) {
            $this->error('404 not found');
        }
        // if (!check_auth('editJfStdoc')) { //不是管理员则进行检测
        //     if ($content['uid'] != is_login()) {
        //         $this->error('404 not found');
        //     }
        // }

        $zuopin = $this->zuopinModel->find($content['id']);


        $this->assign('zuopin_id', $zuopin['id']);
        $content['user'] = query_user(array('id', 'nickname', 'space_url', 'space_link', 'avatar64', 'rank_html', 'signature'), $content['uid']);
        $this->assign('content', $content);
        $this->display();
    }

}